package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.IAsyncService;
import com.heima.common.dto.ResponseResult;
import freemarker.template.TemplateException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author 舌太来
 * @since 2022-04-14
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    @Lazy
    private IAsyncService asyncService;

    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) throws TemplateException, IOException {
        // 需求分析
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        // 判断dto中id是否为空
        if (dto.getId() == null) {
            // id为空 新增文章
            // 保存文章表
            apArticle.setCreatedTime(new Date());
            this.save(apArticle);
            // 保存内容表
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            contentService.save(content);

            //生成静态页 异步线程
            System.out.println(Thread.currentThread().getName()+" 开始调用异步自动审核服务");
            asyncService.createHtml(apArticle,dto.getContent());

            // 返回通用的响应
            return ResponseResult.okResult(apArticle.getId());
        } else {
            // id不为空,修改文章
            this.updateById(apArticle);
            // 修改内容表
            LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();
            update.eq(ApArticleContent::getArticleId, dto.getId());
            update.set(ApArticleContent::getContent, dto.getContent());
            contentService.update(update);
            return ResponseResult.okResult(apArticle.getId());
        }
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 加载文章
     *
     * @param dto
     * @param type 0：最新  1：更多
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {
        // 判断是否是首页加载数据,如果是首页的话,先从redis中查询数据
        if (dto.getLoaddir() == 1) {
            // 先从redis中查询数据,按照分值从大到小排序
            String key = "first_page_article_" + dto.getChannelId();
            long start = 0;
            long end = dto.getSize() - 1;
            Set<String> strings = redisTemplate.opsForZSet().reverseRange(key, start, end);
            //转换成文章集合
            List<ApArticle> articles = new ArrayList<>();
            for (String string : strings) {
                ApArticle article = JSON.parseObject(string, ApArticle.class);
                articles.add(article);
            }
            //如果文章数量够传入的页面显示数据，直接返回文章列表
            if (articles.size() >= dto.getSize()) {
                return ResponseResult.okResult(articles);
            }
        }

        //构造查询条件
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        //判断频道id是否为0
        if (dto.getChannelId() != null && dto.getChannelId() != 0) {
            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        //判断操作类型 上拉 加载更多文章 查询比前端传递的最小发布文章时间更早的文章
        if (type == 1) {
            query.lt(ApArticle::getPublishTime, dto.getMinTime());
        } else {
            //下拉 加载最新文章 查询比前端传递的最大发布时间更晚的文章
            query.gt(ApArticle::getPublishTime, dto.getMaxTime());
        }
        //过滤已下架已删除文章
        query.eq(ApArticle::getIsDelete, false);
        query.eq(ApArticle::getIsDown, false);
        //文章按照发布时间排序
        query.orderByDesc(ApArticle::getPublishTime);
        //查询文章列表
        IPage<ApArticle> page = new Page<>(1, dto.getSize());
        IPage<ApArticle> iPage = this.page(page, query);
        return ResponseResult.okResult(iPage.getRecords());
    }

    /**
     * 查看文章详情
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //查询文章表
        ApArticle article = this.getById(dto.getArticleId());
        //查询内容表
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId,dto.getArticleId());
        ApArticleContent content = contentService.getOne(query);
        //返回定义的格式
        Map<String, Object> map = new HashMap<>();
        map.put("config", article);
        map.put("content", content);
        return ResponseResult.okResult(map);
    }
}
